package com.mathpractise.question.generator;

import com.mathpractise.model.Question;
import com.mathpractise.model.TrainingConfig;
import com.mathpractise.model.enums.QuestionType;
import com.mathpractise.util.RandomUtil;
import org.springframework.stereotype.Component;

/**
 * 20以内加减法题目生成器
 */
@Component
public class TwentyWithinAddSubGenerator extends AbstractQuestionGenerator {
    
    @Override
    public QuestionType getSupportedType() {
        return QuestionType.TWENTY_WITHIN_ADD_SUB;
    }
    
    @Override
    protected Question doGenerateQuestion(TrainingConfig trainingConfig) {
        // 随机决定是加法还是减法
        boolean isAddition = RandomUtil.nextBoolean();
        
        if (isAddition) {
            // 20以内加法
            int num1 = RandomUtil.nextInt(1, 20); // 1-19之间
            int num2 = RandomUtil.nextInt(1, 20 - num1 + 1); // 确保结果不超过20
            
            // 确保不会生成 n+0 或 0+n 的题目（虽然这里不会出现0，但为了保险）
            if (num1 == 0 || num2 == 0) {
                num1 = Math.max(1, num1);
                num2 = Math.max(1, num2);
            }
            
            String expression = num1 + "+" + num2;
            int correctAnswer = num1 + num2;
            
            Question question = new Question();
            question.setExpression(expression);
            question.setCorrectAnswer(correctAnswer);
            
            return question;
        } else {
            // 20以内减法
            int num1 = RandomUtil.nextInt(1, 21); // 被减数在1-20之间
            int num2 = RandomUtil.nextInt(1, num1 + 1); // 减数在1到被减数之间，确保结果非负
            
            // 确保不会生成 n-0 的题目
            if (num2 == 0) {
                num2 = 1;
            }
            
            String expression = num1 + "-" + num2;
            int correctAnswer = num1 - num2;
            
            Question question = new Question();
            question.setExpression(expression);
            question.setCorrectAnswer(correctAnswer);
            
            return question;
        }
    }
}